ConfigTable = ConfigTable or Class("ConfigTable")

---@diagnostic disable-next-line: duplicate-set-field
function ConfigTable:ctor(args)
    self.id = args.id
    self.name = "表"..self.id
    self.desc = "无"
    self._eIdCreator = IdCreator.new()
    self._dicIdCreator = IdCreator.new()
    -- 默认会有一个id列，所以headerIdCreator从2开始
    self._headerIdCreator = IdCreator.new(2)
    self._headers = {
        {
            id = 1,
            name = "id",
            valueInitor = function ()
                return self._eIdCreator:create()
            end
        }
    }
    self._elements = {}
    self._dicPaths = {}
    self._groupPaths = {}
    self._dics = {}
    self:addDicPath(1)
end

function ConfigTable:addDicPath(...)
    local path = {...}
    local dicId = self._dicIdCreator:create()
    self._dicPaths[dicId] = path
    return dicId
end

function ConfigTable:addHeader(header)
    header.id = self._headerIdCreator:create()
    table.insert(self._headers, header)
    return header.id
end

function ConfigTable:addElement()
    local element = ConfigTableElement.new(self)
    table.insert(self._elements, element)
    return element
end

function ConfigTable:get(dicId, keyValue, id)
    local element = self._dics[dicId][keyValue]
    return element:getData(id)
end

function ConfigTable:_createDic(path, depth, dic, elements)
    depth = depth or 1
    dic = dic or {}
    elements = elements or self._elements
    local id = path[depth]
    if depth == #path then
        for i = 1, #elements do
            dic[elements[i]:getData(id)] = elements[i]
        end
    else
        local tbls = {}
        for i = 1, #elements do
            local value = elements[i]:getData(id)
            if not tbls[value] then
                tbls[value] = {}
            end
            table.insert(tbls[value], elements[i])
        end
        for v, e in pairs(tbls) do
            dic[v] = {}
            self:_createDic(path, depth + 1, dic[v], e)
        end
    end
    return dic
end
function ConfigTable:createDics()
    self._dics = {}
    for dicId, path in pairs(self._dicPaths) do
        self._dics[dicId] = self:_createDic(path)
    end
end